package com.joven.core.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.SecureRandom;

/**
 * AES加密器
 *
 * @author padnans
 */
public class AES {

    private static final String KEY = "xaQtm#2022";


    /**
     * AES加密
     */
    public static String encrypt(String cleartext) throws Exception {
        byte[] rawKey = getRawKey(KEY.getBytes("utf-8"));
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
    }

    /**
     * AES解密
     */
    public static String decrypt(String encrypted) throws Exception {
        byte[] rawKey = getRawKey(KEY.getBytes());
        byte[] enc = toByte(encrypted);
        byte[] result = decrypt(rawKey, enc);
        return new String(result, "utf-8");
    }


    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(256, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }


    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    public static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++) {
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        }
        return result;
    }

    public static String toHex(byte[] buf) {
        if (buf == null) {
            return "";
        }
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private final static String HEX = "0123456789ABCDEF";

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

    public static String byte2Base64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        //330802199501154416
//        System.out.println(AES.encrypt("33082219940925003X"));
        System.out.println(AES.encrypt("330802199501154416"));
//        System.out.println(AES.decrypt("7A6BA519CA556FA80A5D1C65C587DA45"));
//        System.out.println(AES.decrypt("8D150478F731458F7E00CC8BB79EEF94003AF95790A1FA45C2192FBD4EB227A7"));
//        System.out.println(AES.decrypt("000714EA9289D5EDEE45431B7049CECC23F905193CBC3D1C84993D0CFB80B98389B0865A30E815CC017D5FD1E48DAF575CF9F425270EBCA09E6E9F6C9E3A796175C34F06F071E73F1EFCA55E226BF3DC"));
//        System.out.println(AES.decrypt("773E940DFE41C940A94736ADC6046EA0D0F27BAE618DFFCD5FDC6EC76A7906D6"));
//        System.out.println(AES.decrypt("0B692EBD5ACB45C82661A8669090D88F2FE41A87064E8D3E4C06F874B58F66A7DC4D325041CDFFE050526ED3D0E26C51"));
                System.out.println(AES.decrypt("AC74C1F1A25DB650AA94C14CD02BCA6BB2F44F337DB45EBE50193906F26470A5"));

//        System.out.println(AES.decrypt("F93F63B965D84F2ECE827978FDB75F05E652DB14CA8BA8A9E2698750996817162A9FB5C7B4C77FC0361B62C9E625CE3FDD81780A97037F0479700AA8323A86671EAF5DE328E56FEC82A6D3232AEB0CCE"));
//        System.out.println(AES.decrypt("773E940DFE41C940A94736ADC6046EA0D0F27BAE618DFFCD5FDC6EC76A7906D6"));
//        System.out.println(AES.decrypt("A9D20C7E516FAC38FE2113F65950AB41158CEF34640763DBE09D707F302CC63B"));
//        System.out.println(AES.decrypt("47B7543D3579034EED1FF1D304837A495B7B54E5155D2290BD023709BEBDC7A6"));
//
//        System.out.println(AES.decrypt("0A567719538265B4F6B73E1320ACD59DBB4D6C2F171A8BFE03467056ECB722AD"));
//        System.out.println(AES.decrypt("1F3A8531F61BCDEE67784ADE60B967803B6D792FB880CCCEE436CC2A00B8DDCF19EA0F45574339A63B90E46AE5AA059F"));
        System.out.println(AES.decrypt("418F5079EBEF85B558DB33C32EFCEC58D141F34DFF3E92FEF190E90696C710A8"));
        System.out.println(AES.decrypt("1F3A8531F61BCDEE67784ADE60B967803B6D792FB880CCCEE436CC2A00B8DDCF19EA0F45574339A63B90E46AE5AA059F"));
        System.out.println(AES.decrypt("0CF61AF05153B4B7AF80391B39AE03BE6DCD09900B7CC220A32A5244A68D757A41553FBDBDEAE3677C23DDD93E3AD3C0D99C692CE22BFA4915E4D2DED5AAB90A"));
    }
}
